package com.topboya.linker.utils;

import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.NetworkInfo.State;
import android.net.Uri;
import android.os.Environment;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;

import com.zhy.view.flowlayout.TagAdapter;

import java.io.File;
import java.lang.reflect.Method;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class AndroidUtils {

    public static final int NET_STATUS_ERROR = 0;

    public static final int NET_STATUS_WIFI = 1;

    public static final int NET_STATUS_MOBILE = 2;


    public static String getVersion(Context context) {
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            String version = info.versionName;
            if (version.contains("ctch1")) {
                version = version.replace("ctch1", "");
            }
            return version;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static boolean isClientNeedUpdate(Context context,
                                             String packageName, String newVersion) {
        boolean tag = false;
        PackageManager pManager = context.getPackageManager();
        try {
            PackageInfo pi = pManager.getPackageInfo(packageName, 0);
            if (pi == null) {
                return false;
            }
            String oldVersion = pi.versionName;
            if (oldVersion == null) {
                return false;
            }
            tag = compareVersion(oldVersion, newVersion);
        } catch (NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return tag;
    }

    public static void installAPK(Context context, String apkPath) {

        File apkFile = new File(apkPath);
        if (apkFile.exists()) {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(Uri.parse("file://" + apkFile.toString()),
                    "application/vnd.android.package-archive");
            context.startActivity(intent);
        }

    }

    public static void uninstallAPK(Context context, String packageID) {

        Uri packageURI = Uri.parse("package:" + packageID);
        Intent intent = new Intent(Intent.ACTION_DELETE, packageURI);
        context.startActivity(intent);
    }

    public static boolean checkApkExist(Context context, String packageName) {

        if (packageName == null || "".equals(packageName))
            return false;
        try {
            ApplicationInfo info = context.getPackageManager()
                    .getApplicationInfo(packageName,
                            PackageManager.GET_UNINSTALLED_PACKAGES);
            if (info != null) {
                return true;
            }
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return false;
    }

    public static void openAPK(Context context, String packageName) {
        try {
            PackageManager pManager = context.getPackageManager();
            PackageInfo pi = pManager.getPackageInfo(packageName, 0);
            Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null);
            resolveIntent.setPackage(pi.packageName);
            List<ResolveInfo> apps = pManager.queryIntentActivities(
                    resolveIntent, 0);
            ResolveInfo ri = apps.iterator().next();
            if (ri != null) {
                String className = ri.activityInfo.name;
                Intent intent = new Intent(Intent.ACTION_MAIN);
                ComponentName cn = new ComponentName(packageName, className);
                intent.setComponent(cn);
                context.startActivity(intent);
            }
        } catch (NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static boolean isAPkExist(Context context, String packageName) {

        try {
            PackageManager pManager = context.getPackageManager();
            PackageInfo pi = pManager.getPackageInfo(packageName, 0);
            Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null);
            resolveIntent.setPackage(pi.packageName);
            List<ResolveInfo> apps = pManager.queryIntentActivities(
                    resolveIntent, 0);
            ResolveInfo ri = apps.iterator().next();
            if (ri != null) {
                return true;
            }
        } catch (NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return false;

    }


    public static boolean isNetworkConnected(Context context) {

        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return mNetworkInfo.isAvailable();
            }
        }
        return false;
    }


    public static int checkNetworkInfo(Context context) {
        ConnectivityManager conMan = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);

        //mobile 3G Data Network
        State mobile = conMan.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
                .getState();

        //wifi
        State wifi = conMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();

        if (wifi == State.CONNECTED || wifi == State.CONNECTING) {
            return NET_STATUS_WIFI;
        } else if (mobile == State.CONNECTED || mobile == State.CONNECTING) {
            return NET_STATUS_MOBILE;
        } else {
            return NET_STATUS_ERROR;
        }

    }


    @SuppressLint("MissingPermission")
    public static String getICCID(Context context) {
        TelephonyManager mTelephonyMgr = (TelephonyManager) context.
                getSystemService(Context.TELEPHONY_SERVICE);
        return mTelephonyMgr.getSimSerialNumber();
    }

    @SuppressLint("MissingPermission")
    public static String getIMSI(Context context) {
        TelephonyManager mTelephonyMgr = (TelephonyManager) context.
                getSystemService(Context.TELEPHONY_SERVICE);
        return mTelephonyMgr.getSubscriberId();
    }

    public static String getIMEI(Context context) {
        TelephonyManager telephonyMgr = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        @SuppressLint("MissingPermission") String imei = telephonyMgr.getDeviceId();
        return imei;
    }


    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }


    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }


    public static boolean compareVersion(String oldVersion, String newVersion) {
        boolean tag = false;
        if (newVersion.contains("ctch1")) {
            newVersion = newVersion.replace("ctch1", "");
        }
        String[] oldVersions = oldVersion.split("[.]");
        String[] newVersions = newVersion.split("[.]");
        if (oldVersions == null || newVersions == null) {
            return tag;
        }
        int length = oldVersions.length < newVersions.length ?
                oldVersions.length : newVersions.length;
        for (int i = 0; i < length; i++) {
            int oldVersionLen = oldVersions[i].length();
            int newVeriosnLen = newVersions[i].length();
            String oldVersionTag = oldVersions[i];
            String newVersionTag = newVersions[i];
            if (oldVersionLen > newVeriosnLen) {
                for (int j = 0; j < (oldVersionLen - newVeriosnLen); j++) {
                    newVersionTag = "0" + newVersionTag;
                }
            } else {
                for (int j = 0; j < (newVeriosnLen - oldVersionLen); j++) {
                    oldVersionTag = "0" + oldVersionTag;
                }
            }
            int ioldVersion = Integer.valueOf(oldVersionTag);
            int inewVersion = Integer.valueOf(newVersionTag);
            if (inewVersion > ioldVersion) {
                tag = true;
                return tag;
            } else if (inewVersion < ioldVersion) {
                tag = false;
                return tag;
            }
        }

        return tag;
    }


    public static String getURLSaveName(String url) {
        String fileName = "";
        fileName = url.substring(url.lastIndexOf("/") + 1, url.length());
        if (fileName.endsWith(".apk")) {
            return fileName;
        } else {
            fileName += ".apk";
        }
        return fileName;
    }

    public static String getSDPath() {
        File sdDir = null;
        try {
            sdDir = Environment.getExternalStorageDirectory();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return sdDir.toString();
    }

    //判断字符串是否含空格
    public static boolean containWhiteSpace(String input) {
        Pattern pattern = Pattern.compile("\\s");
        Matcher matcher = pattern.matcher(input);
        boolean found = matcher.find();
        return found;
    }

    //判断字符串是否含特殊字符
    public static boolean checkStrContainSpecil(String input) {
        if (!input.matches("^[\\da-zA-Z]*$")) {
            return true;//字符串中含特殊字符
        }
        return false;
    }
    public static String getTimeDay(String time) {
        Date timeover = null;
        LogUtils.v("time---------"+time);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        try {
             timeover = sdf.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
            LogUtils.v("-----------------------");
        }
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy年MM月dd日");

        return sdf1.format(timeover);
    }
    public static String getTimeDayHour(String time) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date timeover = null;
        try {
            timeover = sdf.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        SimpleDateFormat sdf1 = new SimpleDateFormat("HH:mm");

        return sdf1.format(timeover);
    }
    //获取当前时间
    public static String getCurrentTime() {
        long time = System.currentTimeMillis();
        Date date = new Date(time);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        return sdf.format(date);
    }

    public static String getNotifyTime(String  date){
        LogUtils.v("data:---->"+date);
        Date timeover = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            timeover = sdf.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy/MM/dd");
        return sdf1.format(timeover);
    }

    public static String getCurrentTime1() {
        long time = System.currentTimeMillis();
        Date date = new Date(time);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        return sdf.format(date);
    }

    public static String getCurrentTimeSH() {
        long time = System.currentTimeMillis();
        Date date = new Date(time);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(date);
    }

    public static String getCurrentTimeSHOfoneHoursLate() {

        long time = System.currentTimeMillis()+1*60*60*1000;
        Date date = new Date(time);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(date);
    }
    //格式化时间
    public static String getFormatTime(String time) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        Date dateBuffer = null;
        try {
            dateBuffer = sdf1.parse(time);
            String trueDate = sdf1.format(dateBuffer);
            return trueDate;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String getBasebandVersion() {
        try {
            Class cl = Class.forName("android.os.SystemProperties");
            Object invoker = cl.newInstance();
            Method m = cl.getMethod("get", new Class[]{String.class, String.class});
            Object result = m.invoke(invoker, new Object[]{"gsm.version.baseband", "no message"});
            return (String) result;
        } catch (Exception e) {

        }
        return "";
    }

    public static String hexStringToString(String s) {
        if (s == null || s.equals("")) {
            return null;
        }
        s = s.replace(" ", "");
        byte[] baKeyword = new byte[s.length() / 2];
        for (int i = 0; i < baKeyword.length; i++) {
            try {
                baKeyword[i] = (byte) (0xff & Integer.parseInt(
                        s.substring(i * 2, i * 2 + 2), 16));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        try {
            s = new String(baKeyword, "gbk");
            new String();
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return s;
    }


    public static String getMD5Str(String customerId) {

        String pwd = "";
        String temp = new StringBuilder(customerId).reverse().toString();
        MessageDigest md;
        try {
            md = MessageDigest.getInstance("MD5");
            md.update(temp.getBytes());
            pwd = new BigInteger(1, md.digest()).toString(16);
        } catch (NoSuchAlgorithmException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        return pwd;
    }

    //字符串转换unicode
    public static String stringToUnicode(String string) {
        StringBuffer unicode = new StringBuffer();
        for (int i = 0; i < string.length(); i++) {
            char c = string.charAt(i);  // 取出每一个字符
            unicode.append(String.format("%04X", Integer.parseInt(Integer.toHexString(c),16)));// 转换为unicode
        }
        return unicode.toString();
    }

    public static String unicode2String(String unicode) {
        StringBuffer string = new StringBuffer();

        for (int i = 0; i < unicode.length(); i=i+4) {

            int data = Integer.parseInt(unicode.substring(i,i+4), 16);
            string.append((char) data);
        }
        return string.toString();
    }
    public static String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }

    public static String  getCurrentTimeDay(){

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日");// HH:mm:ss
        //获取当前时间
        Date date = new Date(System.currentTimeMillis());
        return   simpleDateFormat.format(date);

    }

    public static  String getCurrentTimeHours(){

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");// HH:mm
        //获取当前时间后一个小时时间

        Date date = new Date(System.currentTimeMillis());

        return   simpleDateFormat.format(date);
    }

    public static String getCurrentTimeDayLate(){

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日");// HH:mm
        //获取当前时间后一个小时时间
        long currenttime = System.currentTimeMillis() + 1*60*60*1000;
        Date date = new Date(currenttime);

        return  simpleDateFormat.format(date);
    }
    public static String getCurrentTimeHoursLate(){

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");// HH:mm
        //获取当前时间后一个小时时间
        long currenttime = System.currentTimeMillis() + 1*60*60*1000;
        Date date = new Date(currenttime);

        return   simpleDateFormat.format(date);
    }

     public static String getSelectTime(Date date){

         SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// HH:mm
        return simpleDateFormat.format(date);
     }

    public static String getSelectFullTime(Date date){

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");// HH:mm
        return simpleDateFormat.format(date);
    }
    public static String getSelectDayTime(Date date){

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日");// HH:mm
        return simpleDateFormat.format(date);
    }


    public static String getSelectHoursTime(Date date){

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");// HH:mm

        return simpleDateFormat.format(date);
    }

    public static int pixelToDp(Context context, int pixel) {
        DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
        return pixel < 0 ? pixel : Math.round(pixel / displayMetrics.density);
    }
    public static int dpToPixel(Context context, int dp) {
        DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
        return dp < 0 ? dp : Math.round(dp * displayMetrics.density);
    }
}